﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NUS.ISS.ARS.Web.PageController;
using NUS.ISS.ARS.Common;
using NUS.ISS.ARS.Web.Helper;

namespace NUS.ISS.ARS.Web.Booking
{
    public partial class SearchFlight : BookingBaseController
    {
        string _fromDate, _toDate; 
        const string FROM_DATE_CLIENT_ID = "ctl00$MainContent$txtFromDate";
        const string TO_DATE_CLIENT_ID = "ctl00$MainContent$txtToDate";

        protected void Page_Load(object sender, EventArgs e)
        {
            CurrentPage = "SearchFlight.aspx";
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                BindFlightCities();
                SetControlsIfManageBooking();
                if (!IsManageBooking)
                {
                    ClearSessions();
                }
            }
            else
            {
                if(Request.Form[FROM_DATE_CLIENT_ID] != null)
                    _fromDate = Request.Form[FROM_DATE_CLIENT_ID].ToString();
                if (Request.Form[TO_DATE_CLIENT_ID] != null)
                    _toDate = Request.Form[TO_DATE_CLIENT_ID].ToString();
            }           
        }       

        private void BindFlightCities()
        {
            ddlFromCities.Items.Add("Please select");
            ddlFromCities.AppendDataBoundItems = true;
            ddlFromCities.DataSource = GetAllFlightCities();
            ddlFromCities.DataTextField = "CityName";
            ddlFromCities.DataValueField = "CityId";
            ddlFromCities.DataBind();            

            ddlToCities.Items.Add("Please select");
            ddlToCities.AppendDataBoundItems = true;
            ddlToCities.DataSource = GetAllFlightCities();
            ddlToCities.DataTextField = "CityName";
            ddlToCities.DataValueField = "CityId";
            ddlToCities.DataBind();            
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
			
            if (Page.IsValid)
            {
                try
                {

                    DateTime departDate = DateTime.MinValue;
                    DateTime returnDate = DateTime.MinValue;

                    departDate = PageHelper.ConvertStringToDateTImeDefault(_fromDate).Value;

                    if (divReturnDate.Visible == true)
                    {
                        returnDate = PageHelper.ConvertStringToDateTImeDefault(_toDate).Value;
                    }

                    ReservationData.FromCityId = int.Parse(ddlFromCities.SelectedValue);
                    ReservationData.ToCityId = int.Parse(ddlToCities.SelectedValue);
                    ReservationData.DepartDate = departDate;
                    ReservationData.ReturnDate = returnDate;
                    ReservationData.IsRoundTrip = rblBookingType.SelectedValue == "roundtrip";
                    ReservationData.NumOfAdult = int.Parse(ddlAdult.SelectedValue);
                    ReservationData.NumOfChild = int.Parse(ddlChild.SelectedValue);
                    ReservationData.FromCityName = ddlFromCities.SelectedItem.Text;
                    ReservationData.ToCityName = ddlToCities.SelectedItem.Text;
                    SearchFlights(ReservationData);
                    MoveToNextPage();
                }
                catch (Exception ex)
                {
                    //lblMsg.Text = "Unexpected error ocurred.";
                    //lblMsg.Text = ex.Message;
                }
            }
        }        

        private void SetControlsIfManageBooking()
        {
            if (IsManageBooking)
            {
                var trips = FlightBookingTrips.OrderBy(t => t.FlightDate).ThenBy(t => t.DepartureTime);
                var departTrip = trips.FirstOrDefault();
                if (departTrip != null)
                {
                    //set city dropdowns
                    ddlFromCities.SelectedValue = departTrip.FromCityId.ToString();
                    ddlFromCities.Enabled = false;
                    ddlToCities.SelectedValue = departTrip.ToCityId.ToString();
                    ddlToCities.Enabled = false;

                    //set radio buttons
                    bool isChangingBoth = FlightBookingTrips.Count() > 1;

                    if (isChangingBoth)
                    {
                        rblBookingType.SelectedValue = "roundtrip";
                    }
                    else
                    {
                        rblBookingType.SelectedValue = "oneway";
                    }
                    rblBookingType.Enabled = false;

                    //set adult dropdown
                    List<int> passengerNums = GetNumOfPassengersArrayByBookingRefNo();
                    ddlAdult.SelectedValue = passengerNums[0].ToString();
                    ddlAdult.Enabled = false;
                    ddlChild.SelectedValue = passengerNums[1].ToString();
                    ddlChild.Enabled = false;

                    //set calendars
                    txtFromDate.Text = departTrip.FlightDate.ToShortDateString();                   

                    if (trips.Count() > 1) //round trip
                    {
                        SetReturnDateVisibility(true);
                        var returnTrip = trips.Skip(1).Take(1).First();
                        txtToDate.Text = returnTrip.FlightDate.ToShortDateString();                        
                    }
                    else
                    {
                        SetReturnDateVisibility(false);
                    }
                }
            }
        }

        protected void rblBookingType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblBookingType.SelectedValue == "roundtrip")
            {
                SetReturnDateVisibility(true);
            }
            else
            {
                SetReturnDateVisibility(false);
            }
        }


        private void SetReturnDateVisibility(bool visible)
        {
            divReturnDate.Visible = visible;
        }


        protected void ValidateFromCity(object sender, ServerValidateEventArgs e)
        {
            if (ddlFromCities.SelectedIndex == 0)
            {
                e.IsValid = false;
            }
        }

        protected void ValidateToCity(object sender, ServerValidateEventArgs e)
        {
            if (ddlToCities.SelectedIndex == 0)
            {
                e.IsValid = false;
            }
        }

        protected void ValidateFromDate(object sender, ServerValidateEventArgs e)
        {
            DateTime today = DateTime.Now;
            var departDate = PageHelper.ConvertStringToDateTImeDefault(_fromDate).Value;
            if (departDate <= today)
            {
                e.IsValid = false;
            }
        }

        protected void ValidateToDate(object sender, ServerValidateEventArgs e)
        {
            DateTime today = DateTime.Now;
            var departDate = PageHelper.ConvertStringToDateTImeDefault(_fromDate).Value;
            if (divReturnDate.Visible)
            {
                var returnDate = PageHelper.ConvertStringToDateTImeDefault(_toDate).Value;
                if (returnDate < departDate)
                {
                    e.IsValid = false;
                }
            }
        }
    }
}